package com.cy.cuiyang_admin.filter;

import com.cy.cuiyang_admin.pojo.UserInfo;
import com.cy.cuiyang_admin.util.EncryptUtil;
import com.cy.cuiyang_admin.util.SessionUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Base64;

/**
 * Copyright (C), 2008-2020, 国家电网公司客户服务中心信息运维中心
 * Project:  wxws
 *
 * @author: cuiyang
 * Date:     2020/11/19
 * Description: 过滤器  主要拦截所有的请求，并判断session和cookie
 *              是否有缓存，没有的话，获取请求中的参数，录入缓存中；
 *              @Value("${mx.domain}") 注解的方式获取配置文件中的参数
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
@Component
public class MxSessionFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(MxSessionFilter.class);
    @Value("${mx.domain}")
    private String mxDomain;
    @Value("${mx.cookie-path}")
    private String cookiePath;
    @Value("${mx.max-age:0}")
    private int maxAge;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestURI = httpServletRequest.getRequestURI();
        LOGGER.debug("请求地址....,{}", requestURI);

        UserInfo currentUser = SessionUtil.getCurrentUser(httpServletRequest);
        if (currentUser == null) {
            //session为空
            Cookie[] cookies = httpServletRequest.getCookies();
            Cookie cookie = null;
            if (cookies != null) {
                cookie = Arrays.stream(cookies).filter(o -> "userId".equals(o.getName())).findFirst().orElse(null);
                LOGGER.debug("cookie的值....,{}", cookie);
            }
            if (cookie != null && StringUtils.isNotBlank(cookie.getValue())) {
                LOGGER.info("=========cookie.getValue()==========,{}" + cookie.getValue());
                //解密 写入session
                String userId = EncryptUtil.decrypt(cookie.getValue());
                LOGGER.debug("========== cookie 解密以后的 value:{}", userId);
                if (StringUtils.isNotBlank(userId)) {
                    UserInfo userInfo = new UserInfo();
                    userInfo.setUserName(userId);
                    SessionUtil.setCurrentUser(httpServletRequest, userInfo);
                }

            } else {  //session 和 cookie为空
                String encLoginId = requestURI.substring(requestURI.lastIndexOf("/") + 1);
                try {
//                    String decLoginId = new String(Base64.getDecoder().decode(encLoginId));
//                    if (StringUtils.isNotBlank(decLoginId)) {
//                        String loginId = decLoginId.split("#")[0];
//                        //设置session和cook的值
//                        setCookieAndSession(httpServletRequest, httpServletResponse, loginId);
//                    }
                    setCookieAndSession(httpServletRequest, httpServletResponse, encLoginId);
                } catch (Exception e) {
                    LOGGER.error("解密URL传入的身份信息失败", e);
                }
            }
        } else {
            LOGGER.debug("session里有值，过滤器结束。。");
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 获取到userId  ，设置到session和cook中
     *
     * @param request
     * @param response
     * @param loginId
     */
    private void setCookieAndSession(HttpServletRequest request, HttpServletResponse response, String loginId) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(loginId);
        SessionUtil.setCurrentUser(request, userInfo);
        Cookie cookie = new Cookie("userId", EncryptUtil.encrypt(loginId));
        cookie.setMaxAge(maxAge);
        cookie.setPath(StringUtils.isNoneBlank(cookiePath) ? cookiePath : "/");
        String requestURL = request.getRequestURL().toString();
        requestURL = requestURL.replaceAll("http://","").replaceAll("https://","");
        requestURL = requestURL.substring(0, requestURL.indexOf("/"));
        cookie.setDomain(StringUtils.isNoneBlank(mxDomain) ? mxDomain : requestURL);
        response.addCookie(cookie);
    }
}
